package com.joymart.admin.rest;
import com.joymart.common.error.handling.JoymartBusinessException;
import com.joymart.common.utils.SecurityUtils;
import com.joymart.prepaid.wallet.service.PrepaidWalletService;
import com.joymart.recipient.service.RecipientService;
import com.joymart.user.model.BusinessRole;
import com.joymart.user.model.CachedUser;
import com.joymart.user.model.User;
import com.joymart.user.service.UserCacheManager;
import com.joymart.user.service.UserQueryService;
import com.joymart.user.service.UserService;
import lombok.Data;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

import static com.joymart.common.utils.ValidationUtils.validateNickname;
import static com.joymart.common.utils.ValidationUtils.validatePassword;


@RestController
@RequestMapping("/admin")
public class UserAdminController {

    @Autowired
    private UserCacheManager userCacheManager;
    @Autowired
    private UserService userService;
    @Autowired
    private PrepaidWalletService prepaidWalletService;
    @Autowired
    private RecipientService recipientService;


    @Autowired
    private UserQueryService userQueryService;

    @GetMapping("/users")
    public Page<?> searchUsers(
            @RequestParam(value = "role") String role,
            @RequestParam(value = "username", defaultValue = "") String username,
            @RequestParam(value = "nickname", defaultValue = "") String nickname,
            @RequestParam(value = "pageNo", defaultValue = "0")Integer pageNo,
            @RequestParam(value = "pageSize", defaultValue = "20")Integer pageSize
    ) {

        PageRequest pageRequest = PageRequest.of(pageNo, pageSize);

        if(role.equals("PARTY_A")){
            SecurityUtils.requiresRestAuthority("PartyAUserManagement");
            return userQueryService.searchPartyAUsers(username, nickname,pageRequest);
        }else {
            SecurityUtils.requiresRestAuthority("NonPartyAUserManagement");
            return userQueryService.searchNonPartyAUsers(BusinessRole.valueOf(role), username, nickname, pageRequest);
        }

    }


    @GetMapping("/users/{id}")
    public Object userDetails(@PathVariable String id) {
        return userCacheManager.get(id);
    }

    @GetMapping("/users/{id}/prepaidWallet")
    public Object userPrepaidWalletBalance(@PathVariable String id) {
        return prepaidWalletService.findByUserId(id);
    }


    @GetMapping("/users/{id}/recipients")
    public Object userRecipients(@PathVariable String id) {
       return recipientService.findRecipientsByUserId(id);
    }



    @PutMapping("/users/{userId}/password")
    public void changePassword(@PathVariable String userId, @RequestBody Map<String, String> params) {

        CachedUser cachedUser = userCacheManager.get(userId);
        if(cachedUser.getUser().isPartyA()){
            SecurityUtils.requiresRestAuthority("PartyAUserManagement");
        }else {
            SecurityUtils.requiresRestAuthority("NonPartyAUserManagement");
        }

        String newPassword = params.get("newPassword");
        validatePassword(newPassword);
        userService.changePassword( userId, newPassword);
    }


    /**
     * 对于非A端用户，按照客户要求可以修改其注册手机号
     * @param userId
     * @param params
     */
    @PutMapping("/users/{userId}/mobile")
    public void changeMobile(@PathVariable String userId, @RequestBody Map<String, String> params) {
        CachedUser cachedUser = userCacheManager.get(userId);
        if(cachedUser.getUser().isPartyA()){
            throw new JoymartBusinessException("只能修改普通用户手机号");
        }else {
            SecurityUtils.requiresRestAuthority("NonPartyAUserManagement");
        }

        String newMobile = params.get("newMobile").trim();
        userService.changeUsernameAndMobile(userId, newMobile);
    }

    @PutMapping("/users/{userId}/nickname")
    public void changeNickname(@PathVariable String userId, @RequestBody Map<String, String> params) {

        CachedUser cachedUser = userCacheManager.get(userId);
        if(!cachedUser.getUser().isPartyA()){
            throw new JoymartBusinessException("只能修改内部用户昵称");
        }
        SecurityUtils.requiresRestAuthority("PartyAUserManagement");
        String nickname = params.get("nickname");
        validateNickname(nickname);
        userService.changeNickname(userId, nickname);
    }

    @PostMapping("/users/partyA")
    public void createPartyAUser(@RequestBody PartyAUserParams params) {
        SecurityUtils.requiresRestAuthority("PartyAUserManagement");
        userService.createPartyAUser(params.toUser(), params.getPassword());
    }

    @PostMapping("/users/initialAuShop")
    public void createInitialAuShop(@RequestBody InitialAuShopParams params) {
        SecurityUtils.requiresRestAuthority("SystemSettings");
        userService.createNonPartyAUser(params.toUser(), params.getPassword(),null);
    }

    @Data
    public static class InitialAuShopParams{
        private String nickname;
        private String password;
        private String mobile;

        public User toUser (){
            User user = new User();
            user.setPartyA(false);
            user.setUsername(mobile);
            user.setNickname(nickname);
            user.setMobile(mobile);
            user.setMeta(new JSONObject());
            return user;
        }
    }

    @Data
    public static class PartyAUserParams{
        private String id;
        private String username;
        private String nickname;
        private String password;

        public User toUser() {
            User user = new User();
            user.setId(id);
            user.setPartyA(true);
            user.setNickname(nickname);
            user.setUsername(username);
            user.setMeta(new JSONObject());
            return user;
        }
    }
}
